#include "mainwindow.h"
#include "ui_mainwindow.h"

#include <QDir>
#include <QFileDialog>
#include <QDebug>
#include <QAudioOutput>
#include <QMediaMetaData>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    setWindowTitle(tr("MP3 播放器"));
    QIcon windowIcon(":/images/music.png");

    player = new QMediaPlayer(this);
    QAudioOutput *audioOutput = new QAudioOutput(this);
    player->setAudioOutput(audioOutput);

    //播放位置发生变化
    connect(player, &QMediaPlayer::positionChanged, this, &MainWindow::do_positionChanged);
    //播放源的长度发生变化
    connect(player, &QMediaPlayer::durationChanged, this, &MainWindow::do_durationChanged);
    //播放的文件变化
    connect(player, &QMediaPlayer::sourceChanged, this, &MainWindow::do_sourceChanged);
    //播放器的状态发生变化
    connect(player, &QMediaPlayer::playbackStateChanged, this, &MainWindow::do_playbackStateChanged);
    //元数据发生变化
    connect(player, &QMediaPlayer::metaDataChanged, this, &MainWindow::do_metaDataChanged);

    loopPlay = true;

    resize(611, 490);
}

MainWindow::~MainWindow()
{
    delete ui;
}


void MainWindow::on_btn_add_clicked()
{
    QString curPath = QDir::currentPath();
    QString dlgTitle = "选择要播放的文件" ;
    QString filter = "音频文件(*.mp3 *.wav *.wma);所有文件(*.*)";
    QStringList fileList = QFileDialog::getOpenFileNames(this, dlgTitle, curPath, filter);

    if(fileList.size() < 1){
        return ;
    }

    for(int i=0; i<fileList.size(); i++){
        //qDebug()<<fileList.at(i);
        QFileInfo fileInfo(fileList.at(i));

        QListWidgetItem *aItem = new QListWidgetItem(fileInfo.fileName());
        aItem->setIcon(QIcon(":/images/music.png"));
        //设置用户数据
        aItem->setData(Qt::UserRole, QUrl::fromLocalFile(fileList.at(i)));
        ui->listWidget->addItem(aItem);
    }

    if(player->playbackState() != QMediaPlayer::PlayingState){
        /*当前没播放就从第一首开始播放*/
        ui->listWidget->setCurrentRow(0);
        QUrl source = getUrlFromItem(ui->listWidget->currentItem());
        player->setSource(source);
        player->play();
    }
}

QUrl MainWindow::getUrlFromItem(QListWidgetItem *item)
{
    QVariant  itemData = item->data(Qt::UserRole); //获取用户数据
    QUrl source = itemData.value<QUrl>(); // QVariant 转化为 QUrl

    return source;
}


void MainWindow::on_btn_play_clicked()
{
    if(ui->listWidget->currentRow() < 0){ //没有选择文件
        ui->listWidget->setCurrentRow(0);
    }

    player->setSource(getUrlFromItem(ui->listWidget->currentItem()));
    player->play();
}


void MainWindow::on_btn_pause_clicked()
{
    player->pause();
}


void MainWindow::on_btn_stop_clicked()
{
    player->stop();
}


void MainWindow::on_btn_prev_clicked()
{
    //获取列表中一共有多少首歌
    int count = ui->listWidget->count();
    int curRow = ui->listWidget->currentRow();
    curRow--;
    curRow = curRow<0? count-1:curRow;
    //设置当前行
    ui->listWidget->setCurrentRow(curRow);
    loopPlay = false;
    player->setSource(getUrlFromItem(ui->listWidget->currentItem()));
    player->play();
    loopPlay = ui->cb_cycle->isChecked();

}


void MainWindow::on_btn_next_clicked()
{
    //获取列表中一共有多少首歌
    int count = ui->listWidget->count();
    int curRow = ui->listWidget->currentRow();
    curRow++;

    curRow = curRow>=count? 0: curRow;
    //qDebug()<<curRow;
    ui->listWidget->setCurrentRow(curRow);

    loopPlay = false;
    player->setSource(getUrlFromItem(ui->listWidget->currentItem()));
    player->play();
    loopPlay = ui->cb_cycle->isChecked();

}

void MainWindow::do_positionChanged(qint64 position)
{
    ui->slider_pos->setSliderPosition(position);

    int secs = position/1000;
    int mins = secs/60;
    positionTime = QString::asprintf("%d:%d", mins, secs);
    ui->lb_pos->setText(positionTime + "/" + durationTime);
}

void MainWindow::do_durationChanged(qint64 duration)
{
    ui->slider_pos->setMaximum(duration);

    int secs = duration /1000; //秒
    int mins = secs / 60; //分

    durationTime = QString::asprintf("%d:%d", mins, secs);
    ui->lb_pos->setText(positionTime + "/" + durationTime);
}

void MainWindow::do_sourceChanged(const QUrl &media)
{
    ui->lb_cur_name->setText(media.fileName());
}

void MainWindow::do_playbackStateChanged(QMediaPlayer::PlaybackState newState)
{
    //qDebug()<<"player status: " << newState;
    //播放完一曲后 如果loopPlay为true 自动播放下一曲
    if(newState==QMediaPlayer::StoppedState && loopPlay){
        int count = ui->listWidget->count();
        int curRow = ui->listWidget->currentRow();
        curRow++;
        curRow = curRow>=count? 0: curRow;
        ui->listWidget->setCurrentRow(curRow);
        player->setSource(getUrlFromItem(ui->listWidget->currentItem()));
        player->play();
    }
}

void MainWindow::do_metaDataChanged()
{
    QMediaMetaData metaData = player->metaData(); //获取元数据对象
    QVariant metaTitle = metaData.value(QMediaMetaData::Title);
    QVariant metaAuthor = metaData.value(QMediaMetaData::Author);
    QVariant metaAlbumTitle = metaData.value(QMediaMetaData::AlbumTitle);

    QString content = QString("AlbumTitle:%1\nTitle:%2\nAuthor:%3")
                          .arg(metaAlbumTitle.value<QString>())
                          .arg(metaTitle.value<QString>())
                          .arg(metaAuthor.value<QString>());
    ui->lb_metadata->setText(content);
}


void MainWindow::on_btn_del_clicked()
{
    int index = ui->listWidget->currentRow();
    if(index >= 0){
        QListWidgetItem *item = ui->listWidget->takeItem(index); //删除
        delete item;
    }
}


void MainWindow::on_btn_clear_clicked()
{
    ui->listWidget->clear();
    player->stop();
}


void MainWindow::on_btn_close_clicked()
{
    close();
}


void MainWindow::on_btn_mute_clicked()
{
    /*获取设备当前是否为静音状态*/
    bool mute = player->audioOutput()->isMuted();
    player->audioOutput()->setMuted(!mute);
    if(mute){ //静音状态
        ui->btn_mute->setIcon(QIcon(":/images/volumn.bmp"));
    }
    else{
        ui->btn_mute->setIcon(QIcon(":/images/mute.bmp"));
    }

}


void MainWindow::on_doubleSpinBox_valueChanged(double arg1)
{
    player->setPlaybackRate(arg1);
}


void MainWindow::on_cb_cycle_stateChanged(int arg1)
{

}


void MainWindow::on_slider_volumn_sliderMoved(int position)
{
    player->audioOutput()->setVolume(position / 100.0);
}


void MainWindow::on_slider_pos_sliderMoved(int position)
{
    player->setPosition(position);
}


void MainWindow::on_listWidget_doubleClicked(const QModelIndex &index)
{
    loopPlay = false;
    player->setSource(getUrlFromItem(ui->listWidget->currentItem()));
    player->play();

    loopPlay = ui->cb_cycle->isChecked();
}

